import { Navigate, useLocation } from "react-router-dom";

const ProtectedRoute = ({ children }) => {
  const location = useLocation();
  const isAuthenticated = localStorage.getItem("isAuthenticated") === "true";

  // 如果未登录，重定向到登录页面，并记住当前要访问的页面路径
  if (!isAuthenticated && location.pathname !== "/login") {
    return <Navigate to="/login" state={{ from: location.pathname }} replace />;
  }

  // 如果已登录且尝试访问登录页面，重定向到首页
  if (isAuthenticated && location.pathname === "/login") {
    return <Navigate to="/" replace />;
  }

  return children;
};

export default ProtectedRoute; 